package lab.jsp;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.RemoveException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import ru.ssau.CollectionDAOBeanRemote;
import ru.ssau.CollectionDAOBeanRemoteHome;

/**
 *
 * @author Smike
 */
public abstract class AbstractJSP<T> extends HttpServlet implements HttpJspPage {

    protected CollectionDAOBeanRemote dao;

    protected abstract T getData();

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        _jspService(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        _jspService(request, response);
    }

    @Override
    public void jspInit() {
        // will be implemented by JSP
    }

    @Override
    public void jspDestroy() {
        // will be implemented by JSP
    }

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            dao = ((CollectionDAOBeanRemoteHome) PortableRemoteObject.narrow(new InitialContext().lookup("ejb/MyDAOBean"), CollectionDAOBeanRemoteHome.class)).create();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        if (dao != null) {
            try {
                dao.remove();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
